/**
 * 分页功能相关的数据都放在这里
 * loadPageFunc 为获取分页的数据，返回数据里有total、records、pages这些字段的
 * params 为请求参数，请求之后这里会统一把空的属性过滤掉
 * @returns
 */
import _ from 'lodash'

export function usePagination({
  loadPageFunc: getPage,
  params,
  pageKey,
  sizeKey,
  paramsKey,
  beforeRequest,
  afterRequest
}) {
  // 是否是reload请求
  const isReload = ref(false)

  // 加载中的状态
  const loadingState = reactive({
    // 是否下拉刷新中
    pullDownLoading: false,
    // 是否上拉加载更多种
    infiniteLoading: false,
    // 是否在调用接口
    dataLoading: false,
    isNoMore: false
  })

  // 分页数据
  const paginationState = reactive({
    // 查询出来的所有数据
    list: [],
    // 当前页码
    page: 0,
    // 每页10条
    size: 10,
    // 总条数
    total: 0,
    // 总页数
    pages: 1
  })

  //  重置刷新，用于查询条件变更后刷新列表
  const reload = () => {
    paginationState.page = 0
    isReload.value = true
    loadingState.dataLoading = false
    loadingState.isNoMore = false
    return loadNextPage()
  }

  // 划到底部加载更多
  const loadNextPage = async () => {
    if (loadingState.isNoMore || loadingState.dataLoading) return
    const { page, size, list } = paginationState
    loadingState.dataLoading = true
    loadingState.infiniteLoading = true
    const totalParams = _.cloneDeep(toRaw(params))
    totalParams[pageKey] = page + 1
    totalParams[sizeKey] = size
    delEmptyProp(paramsKey ? totalParams[paramsKey] : totalParams)
    if (paramsKey) {
      delEmptyProp(totalParams)
    }
    try {
      if (beforeRequest) {
        beforeRequest(totalParams)
      }
      const r = await getPage(totalParams)
      if (r.code !== 200) return
      const { current, pages, records, total } = r.data
      if (afterRequest) {
        afterRequest(r.data)
      }
      paginationState.page = current
      paginationState.pages = pages
      paginationState.list = current === 1 ? records : [...list, ...records]
      paginationState.total = total
      if (paginationState.list >= total) {
        loadingState.isNoMore = true
      }
      if (current === 1) {
        window.scrollTo(0, 0)
      }
    } catch (error) {
    } finally {
      loadingState.dataLoading = false
      loadingState.infiniteLoading = false
      loadingState.pullDownLoading = false
      isReload.value = false
    }
  }

  // 把对象空属性去掉
  const delEmptyProp = (args) => {
    const type = typeof args
    if (type !== 'object') return
    if (Array.isArray(args)) return
    const keys = Object.keys(args)
    keys.forEach((k) => {
      const v = args[k]
      if (v === '' || (typeof v === 'object' && _.isEmpty(v))) {
        delete args[k]
      }
      // 把排序字段转对象, 排序的值中没有逗号的说明不需要转换
      if (k === 'sort' && v && typeof v === 'string' && v.indexOf(',') !== -1) {
        const [field, order] = v.split(',')
        args[k] = { field, order }
      }
    })
  }

  return { paginationState, loadNextPage, reload, loadingState }
}
